# -*- coding:utf-8 -*-
# @Author:🎈RedBalloon
# @Time:2022/10/2-0:40
# @File:13-cookie的使用3.py

from urllib.request import Request, build_opener, HTTPCookieProcessor
from http.cookiejar import MozillaCookieJar
from fake_useragent import UserAgent
from urllib.parse import urlencode
# <title>文件存储cookie</title>
# 登录


def get_cookie():
    url = "https://www.itbaizhan.com/login?redirect=https://www.itbaizhan.com/setting.html"
    headers = {
        "User-Agent": UserAgent().random,
    }
    form_data = {
        "phone": "motoseb879@ishyp.com",
        "captcha": 1,
        "code": "195193",
    }

    f_data = urlencode(form_data).encode()
    request = Request(url, headers=headers, data=f_data)
    cookie_jar = MozillaCookieJar()
    handler = HTTPCookieProcessor(cookie_jar)
    opener = build_opener(handler)
    response = opener.open(request)

    # ignore_expires 无论失效或过期都保存下来
    cookie_jar.save("cookie.txt", ignore_expires=True, ignore_discard=True)
    # 保存cookie


# 访问页面
def use_cookie():
    info_url = "https://www.itbaizhan.com/mine.html"
    headers = {
        "User-Agent": UserAgent().random,
    }
    request = Request(info_url, headers=headers)
    cookie_jar = MozillaCookieJar()

    cookie_jar.load("cookie.txt", ignore_expires=True, ignore_discard=True)
    handler = HTTPCookieProcessor(cookie_jar)
    opener = build_opener(handler)
    response = opener.open(request)
    print(response.read().decode())


if __name__ == '__main__':
    # get_cookie()
    use_cookie()